//账单查询住院个人
import React from 'react'
import { DatePicker, Table, Button, Modal, Card, Col, message } from 'antd'
import moment from 'moment';
import { $http } from '../../../containers/config/https'
import InvRecordHospital from './InvRecordHospital'
import RangeDatePicker from 'components/rangePicker/index';
import '../charges/style/style.less'
import store from '../../../store';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import '../style/index.less';
import { $loopPrint } from '../../lodop/Common/Print.js';

const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD' || undefined;

export default class OPOutpatientPersonal extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            data: [],
            StartDate: moment(new Date, dateFormat).subtract(1, 'days'),
            EndDate: moment(new Date, dateFormat).subtract(1, 'days'),
            userInfo: {},
            // 表格数据
            tableData: [],
            showLoading: true,
            // 表格数据总条数
            total: 0,
            page: 1,
            pageSize: 10,
            columns: [],
            languageTable1: {}, // 国际化Table1
            languageTable2: {}, // 国际化Table2
            languageData: {}, // 国际化语言包
            language: {},   // 国际化语言
            languageCode: JSON.parse(window.sessionStorage.userData).language, // 国际化语言标识

        }
        // this.columns = [
        //     {
        //         title: '结算时间',
        //         dataIndex: 'footDataTime',
        //         width: 200,
        //         align: 'center',
        //     },
        //     {
        //         title: '应收金额',
        //         dataIndex: 'patAmt',
        //         width: 100,
        //         align: 'center',
        //     },
        //     {
        //         title: '退款金额',
        //         dataIndex: 'refundAmt',
        //         width: 100,
        //         align: 'center'
        //     },
        //     {
        //         title: '支付方式',
        //         dataIndex: 'payInvAmt',
        //         width: 100,
        //         align: 'center'
        //     },
        //     {
        //         title: '正常发票数量',
        //         dataIndex: 'normalInvNum',
        //         width: 100,
        //         align: 'center'
        //     },
        //     {
        //         title: '正常发票金额',
        //         dataIndex: 'normalInvAmt',
        //         width: 100,
        //         align: 'center'
        //     },
        //     {
        //         title: '作废发票数量',
        //         dataIndex: 'abortInvNum',
        //         width: 100,
        //         align: 'center'
        //     },
        //     {
        //         title: '作废发票金额',
        //         dataIndex: 'abortInvAmt',
        //         width: 100,
        //         align: 'center'
        //     },
        //     {
        //         title: '红冲发票数量',
        //         dataIndex: 'strikeInvNum',
        //         width: 100,
        //         align: 'center'
        //     },
        //     {
        //         title: '红冲发票金额',
        //         dataIndex: 'strikeInvAmt',
        //         width: 100,
        //         align: 'center'
        //     },
        // ]
    }

    //初始化数据
    componentDidMount() {
        this.tableList();
        this.handleQuery()
    }

    onColumnRef = (ref) => {
        console.log(ref)
        this.columnRef = ref;
    }
    // 获取主列表columns
    tableList = (reactCode, compontName) => {
        var data = {
            params: [{
                "reactCode": ["OPHospitalizedPersonal"],
                "compontName": "OPHospitalizedPersonal",
                "type": "C"
            }]
        }
        console.log(1, data)
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let resC = res.result.C
                    let { languageCode } = this.state
                    for (var i = 0; i < resC.length; i++) {
                        resC[i].key = i;
                    }
                    if (languageCode === "EN") {
                        resC.map((item, i) => {
                            item.title = item.enDescripts
                        })
                    }

                    if (languageCode === "CN") {
                        resC.map((item, i) => {
                            item.title = item.descripts
                        })
                    }
                    let arr = res.result && resC.length > 0 ? JSON.parse(JSON.stringify(resC)).map(item => {
                        return {
                            align: item.align,
                            widthNum: parseInt(item.width),
                            width: item.width,
                            dataIndex: item.dataIndex,
                            title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{item.title}</div>,
                            display: item.display,
                            key: item.seqNo
                        }
                    }) : '';
                    let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                    this.setState({
                        columns: filterArr,
                        languageTable1: res.result.B || {},  // 国际化Table1
                        languageTable2: res.result.C || {},  // 国际化Table2
                        languageData: res.result.language || {},  // 国际化语言包
                    }, () => {
                        this.LanCNEN(this.state.languageCode)
                    })
                }
            }
        })
    }

    LanCNEN = (code) => {
        let { languageData } = this.state
        this.setState({
            language: languageData[code]
        })
    }

    // 页码改变的回调，参数是改变后的页码及每页条数
    appPageChange = (page, pageSize) => {
        this.setState({
            page: page,
            pageSize: pageSize,
        }, () => {
            // 重新调用查询方法
            this.handleQuery();
        });
    }

    // 条数改变的回调
    apponShowSizeChange = (current, size) => {
        this.setState({
            page: current,
            pageSize: size,
        }, () => {
            // 重新调用查询方法
            this.handleQuery();
        });
    }

    //基础数据
    handleQuery = () => {
        let { page, pageSize } = this.state;
        let data = {}
        data = {
            params: [{
                "userID": JSON.parse(window.sessionStorage.userData).userID,
                "hospID": JSON.parse(window.sessionStorage.userData).hospID,
                "startDate": this.state.StartDate || '',
                "endDate": this.state.EndDate || '',
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: 'code',
                sortOrder: 'asc'
            }]
        }
        $http.post('urls', this, {
            code: '05100146',
            data: data,
            success: function (res) {
                if (+res.errorCode == 0 && res.result) {
                    let len = res.result.Data.length
                    for (var i = 0; i < len; i++) {
                        res.result.Data[i].key = i;
                    }
                    this.setState({ tableData: res.result.Data, total: res.result.TotalCount, loading: false })
                } else {
                    this.setState({ tableData: [], total: 0, loading: false })
                }
            }
        })
    }
    printData = ()=>{
        let {tableData}=this.state;
        var arr=[]
        console.log(tableData,"table")
        for(var i=0;i<tableData.length;i++){
            arr.push(tableData[i].ID)
            console.log(arr,"arr")
            
        }
        var strs=""
        for (var i = 0; i < arr.length; i++) {
            var str =arr[i]
            console.log(str,"str")
            if (strs===""){
                strs=str
            }else{
                strs=strs+","+str
            }
            // var strs =strs+str+","
            console.log(strs,"字符")
           
        }
        let data=[]
        data = {
            params: [{
                "hospID": JSON.parse(window.sessionStorage.userData).hospID,
                "userID": JSON.parse(window.sessionStorage.userData).userID,
                "IDStr": strs,
                "startDate": this.state.StartDate || '',
                "endDate": this.state.EndDate || '',
                "type": "I",
            }]
        }
        $http.post('urls', this, {
            code: '05100406',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    $loopPrint('', res.result);
                }
            }
        })
    }
    startChange(date) {
        this.setState({
            StartDate: date,
        })
    }

    endChange(date) {
        this.setState({
            EndDate: date,
        })
    }

    // 撤销结账
	revokeFoot = () => {
		let data = {
			params: [{ type: 'I' }]
		}
		$http.post('urls', this, {
			code: '05100356',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					message.success("撤销结账成功！")
					this.handleQuery()
				}
			}
		})
    }
    
    // 取消
    handleCancel = () => {
        this.setState({
            visible: false,
        })
    }

    redireBack = (record) => {
        this.setState({ userInfo: record, visible: true, });
    }

    // 调用子组件的连接事件
    onRef = (ref) => {
        this.child = ref
    }
    // 提供修改page和pageSize的回调函数
    compilePage(page, pageSize) {
        // 修改page，或者pageSize
        this.setState({ page: page, pageSize: pageSize }, () => {
            // 重新调用查询方法
            this.handleQuery();
        })
    }
    // 显示分页总条数
    showTotal(total) {
        return `共 ${total} 条`;
    }
    // 条数改变的回调
    onShowSizeChange = (current, size) => {
        this.compilePage(1, size);
    }
    // 页码改变的回调，参数是改变后的页码及每页条
    onChange = (page, pageSize) => {
        this.compilePage(page, pageSize);
    }
    render() {
        let { language, languageCode } = this.state
        return (
            <div style={{ width: '100%', height: '100%', background: '#F5F7FE' }} className='hosptial-adm-body'>
                <Card bodyStyle={{ padding: '10px' }}>
                    <Col span={6} className='common-col-ul'>
                        <span className='common-span-ui'>{language.OPHospitalizedPersonalselectDate && language.OPHospitalizedPersonalselectDate.descripts + '：'}</span>
                        <RangeDatePicker  format='YYYY-MM-DD' width={290}
                            startDate={this.state.StartDate} endDate={this.state.EndDate}
                            startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} />
                    </Col>
                    {/* <span style={{ display: 'inline-block', marginRight: '60px' }}><RangeDatePicker label={language.OPHospitalizedPersonalselectDate && language.OPHospitalizedPersonalselectDate.descripts+'：'} format='YYYY-MM-DD' width={290}
                        startDate={this.state.StartDate} endDate={this.state.EndDate}
                        startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} /></span> */}
                    <Button style={{ marginRight: '20px' }} type="primary" onClick={this.handleQuery}>{language.OPHospitalizedPersonalquery && language.OPHospitalizedPersonalquery.descripts}</Button>
                    <Button style={{ marginRight: '20px' }} type="primary" onClick={this.revokeFoot} >{'撤销上次结账'}</Button>
                    <Button onClick={() => this.printData()}> {language.OPHospitalizedPersonalprint && language.OPHospitalizedPersonalprint.descripts}</Button>
                </Card>
                <Card style={{ marginTop: 10 }} bodyStyle={{ padding: '10px' }}>
                    <Table
                        dataSource={this.state.tableData}
                        style={{ height: store.getState().tableHeight.y + 110 + 'px' }}
                        scroll={{ x: 900, y: store.getState().tableHeight.y + 110 }}
                        columns={this.state.columns}
                        className='TableA'
                        pagination={false}
                        bordered
                        loading={this.state.loading}
                        onRow={
                            record => {
                                return {
                                    onDoubleClick: event => {
                                        this.redireBack(record)
                                    }
                                }
                            }
                        }
                    />
                    <ColumnAuthoritysModel
                        clientWidth='900px'
                        compontName='OPHospitalizedPersonal'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.tableList}
                    />
                    <CommonPagination size="small" current={this.state.page} total={this.state.total} search='search'
                        onShowSizeChange={this.apponShowSizeChange} complete={true} dataSource={this.state.tableData}
                        onChange={this.appPageChange} />
                    {/* <Pagination
                                showTotal={() => this.showTotal(this.state.total)}
                                size="small"
                                showQuickJumper
                                showSizeChanger
                                defaultCurrent={1}
                                defaultPageSize={10}
                                current={this.state.page}
                                total={this.state.total}
                                onChange={this.onChange}
                                onShowSizeChange={this.onShowSizeChange}
                                style={{ textAlign: "right", marginTop: '13px' }}
                            /> */}

                    <Modal className="Monitor" title={languageCode === "CN" ? '收费明细' : "Charge details"} visible={this.state.visible} onCancel={this.handleCancel} width='1200px' footer={[<Button key="back" onClick={this.handleCancel}>{languageCode === "CN" ? '确认' : " Confirm"}</Button>]}>
                        <InvRecordHospital onRef={this.onRef} userInfo={this.state.userInfo} key={this.state.userInfo.ID} flag='modal' />
                    </Modal>
                </Card>
            </div>
        )
    }
}